#include "picturebox.h"

#include <QPainter>

class PictureBoxPrivate
{
    PictureBoxPrivate(PictureBox *q)
        : q_ptr(q)
    {}

    ~PictureBoxPrivate() {}

    Q_DECLARE_PUBLIC(PictureBox)
    PictureBox *q_ptr;

    QImage m_image;          //图片
    double m_scaling;        //图片缩放比例
    QPointF m_offset;        //图片偏移量
};

PictureBox::PictureBox(QWidget *parent)
    : QWidget(parent)
    , d_ptr(new PictureBoxPrivate(this))
{
}

void PictureBox::setImage(const QImage &image)
{
    if (image.isNull())
        return;

    Q_D(PictureBox);
    d->m_image = image;
    fitWindow();
}

void PictureBox::fitWindow()
{
    Q_D(PictureBox);
    if (d->m_image.isNull())
        return;

    int windowWidth = this->width();
    int windowHeight = this->height();
    int imageWidget = d->m_image.width();
    int imageHeight = d->m_image.height();
    d->m_scaling = qMin(windowWidth * 1.0 / imageWidget, windowHeight  * 1.0 / imageHeight);
    d->m_offset.setX((windowWidth - imageWidget * d->m_scaling) / 2);
    d->m_offset.setY((windowHeight - imageHeight * d->m_scaling) / 2);
    this->update();
}

void PictureBox::paintEvent(QPaintEvent *)
{
    Q_D(PictureBox);
    if (d->m_image.isNull())
        return;

    QPainter painter(this);
    painter.save();

    //绘制图片
    QPixmap pixmap = QPixmap::fromImage(d->m_image);
    painter.translate(d->m_offset);
    painter.scale(d->m_scaling, d->m_scaling);
    painter.drawPixmap(0, 0, pixmap);

    painter.restore();
}

void PictureBox::resizeEvent(QResizeEvent *event)
{
    fitWindow();
}
